package com.yf.exam.modules.user.exam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.exam.core.api.dto.PagingReqDTO;
import com.yf.exam.modules.paper.entity.ExamApply;
import com.yf.exam.modules.paper.service.ExamApplyService;
import com.yf.exam.modules.sys.user.dto.response.SysUserLoginDTO;
import com.yf.exam.modules.sys.user.entity.SysUser;
import com.yf.exam.modules.sys.user.service.SysUserService;
import com.yf.exam.modules.user.UserUtils;
import com.yf.exam.modules.user.exam.dto.request.UserExamReqDTO;
import com.yf.exam.modules.user.exam.dto.response.UserExamRespDTO;
import com.yf.exam.modules.user.exam.entity.UserExam;
import com.yf.exam.modules.user.exam.mapper.UserExamMapper;
import com.yf.exam.modules.user.exam.service.UserExamService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 考试记录业务实现类
 * </p>
 *
 * @author 聪明笨狗
 * @since 2020-09-21 15:13
 */
@Service
public class UserExamServiceImpl extends ServiceImpl<UserExamMapper, UserExam> implements UserExamService {
    @Autowired
    private ExamApplyService examApplyService;
    @Autowired
    private SysUserService sysUserService;

    @Value("${exam-order-id}")
    private List<String> examOrderId;
    @Value("${exam-limit}")
    private Integer examLimit;

    @Override
    public IPage<UserExamRespDTO> paging(PagingReqDTO<UserExamReqDTO> reqDTO) {
        //转换结果
        IPage<UserExamRespDTO> pageData = baseMapper.paging(reqDTO.toPage(), reqDTO.getParams());
        return pageData;
    }

    @Override
    public IPage<UserExamRespDTO> myPaging(PagingReqDTO<UserExamReqDTO> reqDTO) {
        UserExamReqDTO params = reqDTO.getParams();
        if (Objects.isNull(params)) {
            params = new UserExamReqDTO();
        }
        params.setUserId(UserUtils.getUserId());
        //转换结果
        IPage<UserExamRespDTO> pageData = baseMapper.paging(reqDTO.toPage(), params);
        return pageData;
    }

    @Override
    public void joinResult(String userId, String examId, Integer score, final boolean passed, SysUserLoginDTO user, String paperId) {
        Date now = new Date();
        QueryWrapper<ExamApply> examApplyWrapper = new QueryWrapper<>();
        String userName;
        if (Objects.nonNull(user)) { // 用户前端请求
            userName = user.getUserName();
        } else {
            SysUser sysUser = sysUserService.getById(userId);
            if (Objects.nonNull(sysUser)) {
                userName = sysUser.getUserName();
            } else {
                userName = null;
            }
        }
        log.error("userName参数：" + userName);
        examApplyWrapper
                .lambda()
                .eq(ExamApply::getIsApply, 1)
                .and(qu -> qu
                        .eq(ExamApply::getUserName, userName)
                        .or()
                        .eq(ExamApply::getPhone, userName)
                )
                .orderByDesc(ExamApply::getCreateTime)
                .last(" LIMIT 1 ")
        ; // 查出最新的已通过的考试申请
        ExamApply examApply = examApplyService.getBaseMapper().selectOne(examApplyWrapper);
        if (Objects.nonNull(examApply) && Objects.nonNull(examApply.getId())) {
            {
                UpdateWrapper<ExamApply> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda()
                        .eq(ExamApply::getId, examApply.getId())
                        .eq(ExamApply::getAllPass, 0) // 未考试
                        .set(ExamApply::getAllPass, 1); // 考试中
                examApplyService.getBaseMapper().update(null, updateWrapper); // 未考试的申请置为考试中
            }
        }
        // 查询条件
        QueryWrapper<UserExam> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(UserExam::getUserId, userId)
                .eq(UserExam::getExamId, examId)
        ; // 对应的申请记录是否考试过
        if (!Objects.isNull(examApply) && !Objects.isNull(examApply.getId())) {
            wrapper
                    .lambda()
                    .eq(UserExam::getApplyId, examApply.getId());
        }
        UserExam record = this.getOne(wrapper, false);
        if (Objects.isNull(record)) {
            record = new UserExam();
            record.setCreateTime(now);
            record.setUpdateTime(now);
            record.setUserId(userId);
            record.setExamId(examId);
            record.setMaxScore(score);
            record.setPassed(passed);
            record.setPaperId(paperId);
            if (Objects.nonNull(examApply) && Objects.nonNull(examApply.getId())) {
                record.setApplyId(examApply.getId());
            }
            this.save(record);
        }
        // 修复低分数不加入统计问题
        record.setTryCount((Objects.nonNull(record.getTryCount()) ? record.getTryCount() : 0) + 1);
        record.setUpdateTime(now);
        if (record.getMaxScore() < score) {
            record.setMaxScore(score);
            record.setPassed(passed);
            record.setPaperId(paperId);
        }
        if (StringUtils.isEmpty(record.getPaperId())) {
            record.setPaperId(paperId);
        }
        this.updateById(record);

        if (Objects.nonNull(examApply) && Objects.nonNull(examApply.getId()) && examOrderId.contains(examId) && passed) { // 必考科目通过时，回填申请通过
            UpdateWrapper<ExamApply> updateWrapper = new UpdateWrapper<>();
            updateWrapper
                    .lambda()
                    .eq(ExamApply::getId, examApply.getId())
                    .set(ExamApply::getAllPass, 2); // 通过
            examApplyService.getBaseMapper().update(null, updateWrapper);
//            Integer noPassCount;
//            wrapper = new QueryWrapper<>();
//            wrapper.lambda()
//                    .eq(UserExam::getUserId, userId)
//                    .eq(UserExam::getPassed, false) // 失败
//                    .eq(UserExam::getApplyId, examApply.getId()) // 该次申请
//                    .gt(UserExam::getTryCount, examLimit) // 单次考试 大于三次尝试
//                    .in(UserExam::getExamId, examOrderId) // 必考
//            ; // 本次申请，考试了3次以上仍然不通过的考试
//            noPassCount = this.baseMapper.selectCount(wrapper);
//            if (noPassCount >= 1) {
//                UpdateWrapper<ExamApply> updateWrapper = new UpdateWrapper<>();
//                updateWrapper.lambda()
//                        .eq(ExamApply::getId, examApply.getId())
//                        .set(ExamApply::getAllPass, 3); // 未通过
//                examApplyService.getBaseMapper().update(null, updateWrapper);
//                return;
//            }
//            Integer passCount;
//            wrapper = new QueryWrapper<>();
//            wrapper.lambda()
//                    .eq(UserExam::getUserId, userId)
//                    .eq(UserExam::getApplyId, examApply.getId())
//                    .eq(UserExam::getPassed, true)
//                    .le(UserExam::getTryCount, examLimit) // 单次考试 小于三次尝试
//                    .in(UserExam::getExamId, examOrderId) // 必考考试
//            ;
//            passCount = this.baseMapper.selectCount(wrapper);
//            if (passCount >= examOrderId.size()) { // 必考考试全通过
//                UpdateWrapper<ExamApply> updateWrapper = new UpdateWrapper<>();
//                updateWrapper
//                        .lambda()
//                        .eq(ExamApply::getId, examApply.getId())
//                        .set(ExamApply::getAllPass, 2); // 通过
//                examApplyService.getBaseMapper().update(null, updateWrapper);
//            }
        }
    }

    @Override
    public List<UserExamRespDTO> getApplyExamResult(Long applyId, String examId) {
        return baseMapper.getListFromApplyId(applyId, examId);
    }
}
